package tugas.akhir.jason.data.export;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.util.Log;

public class XmlDatabaseExporter {
	private static String LOG_TAG = "XmlDatabaseExporter";
	private static XmlDatabaseExporter exporterInstance;
	
	private DocumentBuilderFactory documentBuilderFactory;
	
	public static XmlDatabaseExporter getInstance() {
		if(exporterInstance == null) {
			exporterInstance = new XmlDatabaseExporter();
		}
		return exporterInstance;
	}
	
	protected XmlDatabaseExporter() {
		documentBuilderFactory = DocumentBuilderFactory.newInstance();
	}
	
	public String export() throws DatabaseExporterException {
		try {
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.newDocument();
			
			// Pertama, create root element.
			Element rootElement = document.createElement("data");
			document.appendChild(rootElement);
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			
			DOMSource domSource = new DOMSource(document);
			StreamResult streamResult = new StreamResult();
			
			transformer.transform(domSource, streamResult);
			
			return streamResult.toString();
		} catch (ParserConfigurationException e) {
			Log.e(LOG_TAG, "Exporter throw an error with message : " + e.getMessage(), e);
			throw new DatabaseExporterException(e);
		} catch (TransformerConfigurationException e) {
			Log.e(LOG_TAG, "Exporter throw an error with message : " + e.getMessage(), e);
			throw new DatabaseExporterException(e);
		} catch (TransformerException e) {
			Log.e(LOG_TAG, "Exporter throw an error with message : " + e.getMessage(), e);
			throw new DatabaseExporterException(e);
		}
	}
	
	private void populateTableNode(String tableName, Element tableNode) {
		
	}
}
